package net.shopxx.action.shop;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.shopxx.bean.ProductImage;
import net.shopxx.bean.SystemConfig;
import net.shopxx.bean.SystemConfig.PointType;
import net.shopxx.entity.Area;
import net.shopxx.entity.Brand;
import net.shopxx.entity.Color;
import net.shopxx.entity.Product;
import net.shopxx.entity.ProductAttribute;
import net.shopxx.entity.ProductCategory;
import net.shopxx.entity.ProductColor;
import net.shopxx.entity.ProductProperties;
import net.shopxx.entity.ProductType;
import net.shopxx.entity.Productitem;
import net.shopxx.entity.Properties;
import net.shopxx.entity.PropertiesValue;
import net.shopxx.entity.Product.WeightUnit;
import net.shopxx.entity.ProductAttribute.AttributeType;
import net.shopxx.service.BrandService;
import net.shopxx.service.ColorService;
import net.shopxx.service.MemberService;
import net.shopxx.service.MessageService;
import net.shopxx.service.ProductAttributeService;
import net.shopxx.service.ProductCategoryService;
import net.shopxx.service.ProductImageService;
import net.shopxx.service.ProductPropertiesService;
import net.shopxx.service.ProductService;
import net.shopxx.service.ProductTypeService;
import net.shopxx.util.SerialNumberUtil;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import com.opensymphony.xwork2.interceptor.annotations.InputConfig;
import com.opensymphony.xwork2.validator.annotations.IntRangeFieldValidator;
import com.opensymphony.xwork2.validator.annotations.RequiredFieldValidator;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.Validations;

/**
 * 前台Action类 - 会员中心
 */

@ParentPackage("member")
public class TraderCenterAction extends BaseShopAction {

	private static final long serialVersionUID = -3568504222758246021L;

	private String categoryId;
	
	private ProductCategory productCategory;

	private List<ProductCategory> rootCategoryList;
	
	private Set<Properties> propertieSet;

	private File[] productImages;
	private String[] productImagesFileName;
	private String[] productImageParameterTypes;
	private String[] productImageIds;
	
	private ProductProperties[] ProductPropertieses;
	
	private File[] colorImages;
	private String[] colorImageIds;
	private String[] descs;
	
	private String[] productitemPrice;
	private String[] productitemCount;
	private String[] productitemSn;
	private String[] colorIds;
	private String[] sizeIds;
	
	private String[] propertiesIds;
	private String[] propertiesValues;
	private String[] propertiesLables;
	
	
	private Product product;

	@Resource
	private ProductService productService;
	@Resource
	private ProductCategoryService productCategoryService;
	@Resource
	private BrandService brandService;
	@Resource
	private ProductTypeService productTypeService;
	@Resource
	private ProductAttributeService productAttributeService;
	@Resource
	private ProductImageService productImageService;
	@Resource
	private MemberService memberService;
	@Resource
	private MessageService messageService;
	@Resource
	private ColorService colorService;
	@Resource
	private ProductPropertiesService productPropertiesService;
	

	// 会员中心首页
	public String index() {
		return "index";
	}

	public String productCategory() {
		return "productCategory";
	}

	// 添加购物车项
	@SuppressWarnings("unchecked")
	@InputConfig(resultName = "error")
	public String ajaxGetSubCategory() {
		
		String path = getParameter("path");
		if (StringUtils.contains(path,  Area.PATH_SEPARATOR)) {
			categoryId = StringUtils.substringAfterLast(path, Area.PATH_SEPARATOR);
		} else {
			categoryId = path;
		}
		List<ProductCategory> childrenAreaList = new ArrayList<ProductCategory>();
		if (StringUtils.isEmpty(categoryId)) {
			childrenAreaList = productCategoryService.getRootProductCategoryList();
		} else {
			childrenAreaList = new ArrayList<ProductCategory>(productCategoryService.load(categoryId).getChildren());
		}
		
		
		List<Map<String, String>> optionList = new ArrayList<Map<String, String>>();
		for (ProductCategory area : childrenAreaList) {
			Map<String, String> map = new HashMap<String, String>();
			map.put("title", area.getName());
			map.put("value", area.getId());
			optionList.add(map);
		}
		JSONArray jsonArray = JSONArray.fromObject(optionList);
		return ajaxJson(jsonArray.toString());
	}

	public String publish() {
		productCategory = productCategoryService.load(categoryId);
		
		System.out.println(productCategory.getProductSize()
				.getPropertiesValueList().size());
		
//		propertieSet= productCategory.getPropertiesSet();
		return "publish";
	}
	
	public String edit()
	{
		product = productService.load(id);
		return "edit";
	}
	
	@Validations(
			requiredStrings = {
				@RequiredStringValidator(fieldName = "product.name", message = "商品名称不允许为空!") 
			}, 
			requiredFields = {
				@RequiredFieldValidator(fieldName = "product.price", message = "销售价不允许为空!"),
				@RequiredFieldValidator(fieldName = "product.marketPrice", message = "市场价不允许为空!"),
				@RequiredFieldValidator(fieldName = "product.weight", message = "商品重量不允许为空!"),
				@RequiredFieldValidator(fieldName = "product.weightUnit", message = "商品重量单位不允许为空!"),
				@RequiredFieldValidator(fieldName = "product.isMarketable", message = "是否上架不允许为空!"),
				@RequiredFieldValidator(fieldName = "product.isBest", message = "是否精品不允许为空!"),
				@RequiredFieldValidator(fieldName = "product.isNew", message = "是否新品不允许为空!"),
				@RequiredFieldValidator(fieldName = "product.isHot", message = "是否热销不允许为空!"),
				@RequiredFieldValidator(fieldName = "product.productCategory.id", message = "所属分类不允许为空!")
			},
			intRangeFields = {
				@IntRangeFieldValidator(fieldName = "product.point", min = "0", message = "积分必须为零或正整数!"),
				@IntRangeFieldValidator(fieldName = "product.store", min = "0", message = "库存必须为零或正整数!")
			}
		)
		@InputConfig(resultName = "error")
	public String save() {
		if (product.getPrice().compareTo(new BigDecimal("0")) < 0) {
			addActionError("销售价不允许小于0");
			return ERROR;
		}
		if (product.getMarketPrice().compareTo(new BigDecimal("0")) < 0) {
			addActionError("市场价不允许小于0");
			return ERROR;
		}
		if (product.getWeight() < 0) {
			addActionError("商品重量只允许为正数或零!");
			return ERROR;
		}
		if (StringUtils.isNotEmpty(product.getProductSn())) {
			if (productService.isExist("productSn", product.getProductSn())) {
				addActionError("货号重复,请重新输入!");
				return ERROR;
			}
		} else {
			String productSn = SerialNumberUtil.buildProductSn();
			product.setProductSn(productSn);
		}
		ProductType productType = product.getProductType();
		if (productType != null && StringUtils.isNotEmpty(productType.getId())) {
			productType = productTypeService.load(productType.getId());
		} else {
			productType = null;
		}
		
		if (productType != null) {
			Map<ProductAttribute, List<String>> productAttributeMap = new HashMap<ProductAttribute, List<String>>();
			List<ProductAttribute> enabledProductAttributeList = productAttributeService.getEnabledProductAttributeList(productType);
			for (ProductAttribute productAttribute : enabledProductAttributeList) {
				String[] parameterValues = getParameterValues(productAttribute.getId());
				if (productAttribute.getIsRequired() && (parameterValues == null || parameterValues.length == 0 || StringUtils.isEmpty(parameterValues[0]))) {
					addActionError(productAttribute.getName() + "不允许为空!");
					return ERROR;
				}
				if (parameterValues != null && parameterValues.length > 0 && StringUtils.isNotEmpty(parameterValues[0])) {
					if (productAttribute.getAttributeType() == AttributeType.number) {
						Pattern pattern = Pattern.compile("^-?(?:\\d+|\\d{1,3}(?:,\\d{3})+)(?:\\.\\d+)?");
						Matcher matcher = pattern.matcher(parameterValues[0]);
						if (!matcher.matches()) {
							addActionError(productAttribute.getName() + "只允许输入数字!");
							return ERROR;
						}
					}
					if (productAttribute.getAttributeType() == AttributeType.alphaint) {
						Pattern pattern = Pattern.compile("[a-zA-Z]+");
						Matcher matcher = pattern.matcher(parameterValues[0]);
						if (!matcher.matches()) {
							addActionError(productAttribute.getName() + "只允许输入字母!");
							return ERROR;
						}
					}
					if (productAttribute.getAttributeType() == AttributeType.date) {
						Pattern pattern = Pattern.compile("\\d{4}[\\/-]\\d{1,2}[\\/-]\\d{1,2}");
						Matcher matcher = pattern.matcher(parameterValues[0]);
						if (!matcher.matches()) {
							addActionError(productAttribute.getName() + "日期格式错误!");
							return ERROR;
						}
					}
					if (productAttribute.getAttributeType() == AttributeType.select || productAttribute.getAttributeType() == AttributeType.checkbox) {
						List<String> attributeOptionList = productAttribute.getAttributeOptionList();
						for (String parameterValue : parameterValues) {
							if (!attributeOptionList.contains(parameterValue)) {
								addActionError("参数错误!");
								return ERROR;
							}
						}
					}
					productAttributeMap.put(productAttribute, Arrays.asList(parameterValues));
				}
			}
//			product.setProductAttributeMap(productAttributeMap);
		} else {
//			product.setProductAttributeMap(null);
		}
		product.setProductType(productType);

		if (productImages != null) {
			String allowedUploadImageExtension = getSystemConfig().getAllowedUploadImageExtension().toLowerCase();
			if (StringUtils.isEmpty(allowedUploadImageExtension)) {
				addActionError("不允许上传图片文件!");
				return ERROR;
			}
			for(int i = 0; i < productImages.length; i ++) {
				String productImageExtension =  StringUtils.substringAfterLast(productImagesFileName[i], ".").toLowerCase();
				String[] imageExtensionArray = allowedUploadImageExtension.split(SystemConfig.EXTENSION_SEPARATOR);
				if (!ArrayUtils.contains(imageExtensionArray, productImageExtension)) {
					addActionError("只允许上传图片文件类型: " + allowedUploadImageExtension + "!");
					return ERROR;
				}
				if (getSystemConfig().getUploadLimit() != 0 && productImages[i].length() > getSystemConfig().getUploadLimit() * 1024) {
					addActionError("此上传文件大小超出限制!");
					return ERROR;
				}
			}
		}
		
		if (StringUtils.isEmpty(product.getBrand().getId())) {
			product.setBrand(null);
		}
		
		if (getSystemConfig().getPointType() == PointType.productSet) {
			if (product.getPoint() == null) {
				addActionError("积分不允许为空!");
				return ERROR;
			}
		} else {
			product.setPoint(0);
		}
		
		List<ProductImage> productImageList = new ArrayList<ProductImage>();
		if (productImages != null && productImages.length > 0) {
			for(int i = 0; i < productImages.length; i ++) {
				ProductImage productImage = productImageService.buildProductImage(productImages[i]);
				productImageList.add(productImage);
			}
		}
		product.setProductImageList(productImageList);
		product.setFreezeStore(0);
		product.setFavoriteMemberSet(null);
		product.setMember(this.getLoginMember());
		
		// 颜色
		List<ProductColor> colorList = new ArrayList<ProductColor>();
		if (colorImages != null && colorImages.length > 0) {
			for(int i = 0; i < colorImages.length; i ++) {
				if(colorImages[i] == null)
				{
					continue;
				}
				ProductColor productColor = new ProductColor();
				String savePath = productImageService.saveFile(colorImages[i]);
				productColor.setImgUrl(savePath);
				
				Color color = new Color();
				color.setId(colorImageIds[i]);
				productColor.setColor(color);
				productColor.setDescript(descs[i]);
				productColor.setProduct(product);
				colorList.add(productColor);
			}
		}
		product.setProductColorList(colorList);
		
		//productitem
		Set<Productitem> itemSet = new HashSet<Productitem>();
		if(colorIds != null && colorIds.length > 0)
		{
			for (int j = 0; j < colorIds.length; j++) {
				Productitem item = new Productitem();
				Color color = new Color();
				color.setId(colorIds[j]);
				
				item.setColor(color);
				item.setStore(Integer.parseInt(productitemCount[j]));
				item.setPrice(new BigDecimal(productitemPrice[j]));
				item.setItemSn(productitemSn[j]);
				item.setFreezeStore(0);
				PropertiesValue sizeObj = new PropertiesValue();
				sizeObj.setId(sizeIds[j]);
				item.setPropertiesValue(sizeObj);
				item.setProduct(product);
				itemSet.add(item);
			}
		}
		else
		{
			Productitem item = new Productitem();
			item.setItemSn(product.getProductSn());
			item.setStore(product.getStore());
			item.setPrice(product.getPrice());
			item.setFreezeStore(0);
			item.setProduct(product);
			itemSet.add(item);
		}
		
		product.setProductitemSet(itemSet);
		
		//properties
		List<ProductProperties> productPropertiesList = new ArrayList<ProductProperties>();
		if (propertiesIds != null && propertiesIds.length > 0) {
			for(int i = 0; i < propertiesIds.length; i ++) {
				if(propertiesIds[i] == null)
				{
					continue;
				}
				ProductProperties productProperties = new ProductProperties();
				productProperties.setLable(propertiesLables[i]);
				productProperties.setValue(propertiesValues[i]);
				
				Properties properties = new Properties();
				properties.setId(propertiesIds[i]);
				productProperties.setProperties(properties);
				productProperties.setProduct(product);
				productPropertiesList.add(productProperties);
			}
		}
		product.setProductPropertiesList(productPropertiesList);
//		product.setProductCategory(productCategory);
		productService.save(product);
//		flushCache();
		redirectionUrl = "trader_center!productCategory.action";
		return "success";
	}
	

	// 获取未读消息数量
	public Long getUnreadMessageCount() {
		return messageService.getUnreadMessageCount(getLoginMember());
	}

	public String getCategoryId() {
		return categoryId;
	}

	public void setCategoryId(String categoryId) {
		this.categoryId = categoryId;
	}

	public List<ProductCategory> getRootCategoryList() {
		return rootCategoryList;
	}

	public void setRootCategoryList(List<ProductCategory> rootCategoryList) {
		this.rootCategoryList = rootCategoryList;
	}

	public Set<Properties> getPropertieSet() {
		return propertieSet;
	}

	public void setPropertieSet(Set<Properties> propertieSet) {
		this.propertieSet = propertieSet;
	}

	public File[] getProductImages() {
		return productImages;
	}

	public void setProductImages(File[] productImages) {
		this.productImages = productImages;
	}

	public String[] getProductImagesFileName() {
		return productImagesFileName;
	}

	public void setProductImagesFileName(String[] productImagesFileName) {
		this.productImagesFileName = productImagesFileName;
	}

	public String[] getProductImageParameterTypes() {
		return productImageParameterTypes;
	}

	public void setProductImageParameterTypes(String[] productImageParameterTypes) {
		this.productImageParameterTypes = productImageParameterTypes;
	}

	public String[] getProductImageIds() {
		return productImageIds;
	}

	public void setProductImageIds(String[] productImageIds) {
		this.productImageIds = productImageIds;
	}

	public Product getProduct() {
		return product;
	}

	public void setProduct(Product product) {
		this.product = product;
	}
	
	// 获取所有品牌
	public List<Brand> getAllBrand() {
		return brandService.getAll();
	}
	
	// 获取所有重量单位
	public List<WeightUnit> getAllWeightUnit() {
		List<WeightUnit> allWeightUnit = new ArrayList<WeightUnit>();
		for (WeightUnit weightUnit : WeightUnit.values()) {
			allWeightUnit.add(weightUnit);
		}
		return allWeightUnit;
	}
	
	public List<Color> getAllColor()
	{
		return colorService.getAll();
	}

	public ProductProperties[] getProductPropertieses() {
		return ProductPropertieses;
	}

	public void setProductPropertieses(ProductProperties[] productPropertieses) {
		ProductPropertieses = productPropertieses;
	}

	public ProductCategory getProductCategory() {
		return productCategory;
	}

	public void setProductCategory(ProductCategory productCategory) {
		this.productCategory = productCategory;
	}

	public File[] getColorImages() {
		return colorImages;
	}

	public void setColorImages(File[] colorImages) {
		this.colorImages = colorImages;
	}

	public String[] getColorImageIds() {
		return colorImageIds;
	}

	public void setColorImageIds(String[] colorImageIds) {
		this.colorImageIds = colorImageIds;
	}

	public String[] getProductitemPrice() {
		return productitemPrice;
	}

	public void setProductitemPrice(String[] productitemPrice) {
		this.productitemPrice = productitemPrice;
	}

	public String[] getProductitemCount() {
		return productitemCount;
	}

	public void setProductitemCount(String[] productitemCount) {
		this.productitemCount = productitemCount;
	}

	public String[] getProductitemSn() {
		return productitemSn;
	}

	public void setProductitemSn(String[] productitemSn) {
		this.productitemSn = productitemSn;
	}

	public String[] getColorIds() {
		return colorIds;
	}

	public void setColorIds(String[] colorIds) {
		this.colorIds = colorIds;
	}

	public String[] getSizeIds() {
		return sizeIds;
	}

	public void setSizeIds(String[] sizeIds) {
		this.sizeIds = sizeIds;
	}

	public String[] getDescs() {
		return descs;
	}

	public void setDescs(String[] descs) {
		this.descs = descs;
	}

	public String[] getPropertiesIds() {
		return propertiesIds;
	}

	public void setPropertiesIds(String[] propertiesIds) {
		this.propertiesIds = propertiesIds;
	}

	public String[] getPropertiesValues() {
		return propertiesValues;
	}

	public void setPropertiesValues(String[] propertiesValues) {
		this.propertiesValues = propertiesValues;
	}

	public String[] getPropertiesLables() {
		return propertiesLables;
	}

	public void setPropertiesLables(String[] propertiesLables) {
		this.propertiesLables = propertiesLables;
	}
}